package com.turato.method;


/**
 * @author tuhao
 * @date 2021/1/16 3:06 下午
 * @desc 去除代码中的 if-else
 */
public class RemoveIfElse {
    /**
     * 交税案例
     */
    public void caseOne() {
        // 收入,税
        double income = 1000, tax = 0;
        if (income <= 2000) {
            tax = 0;
        } else if (income <= 3000) {
            tax = 0.15 * (income - 2000);
        } else if (income <= 5000) {
            tax = 30 + 0.2 * (income - 3000);
        } else {
            tax = 0.5 * income;
        }
    }

    /**
     * 可读性强，但是如果要对5000以上的薪资又细化收税的规则，
     * 则违反开闭原则，需要对原来的代码进行修改
     * @return
     */
    public double testOne() {
        // 收入,税
        double income = 1000, tax = 0;
        if (income <= 2000) {
            return tax = 0;
        }

        if (income <= 3000) {
            return tax = 0.15 * (income - 2000);
        }
        if (income <= 5000) {
            return tax = 30 + 0.2 * (income - 3000);
        }
        if (income > 5000) {
            return tax = 0.5 * income;
        }
        return tax;
    }


    /*---------------- 使用 switch case -------------*/

    public void testTwo() {
        // 收入,税
        double income = 1000, tax = 0;
        // 转换
        int level = salaryLevel(income);
        switch (level) {
            case 0: tax = 0;
            break;
            case 1: tax = 0.15 * (income - 2000);
            break;
            case 2: tax = 30 + 0.2 * (income - 3000);
            break;
            default: tax = 0.5 * income;
        }

    }

    /**
     * 计算薪资级别
     * @param income 薪资
     * @return
     */
    private int salaryLevel(double income) {
        if (income <= 2000) {
            return 0;
        }

        if (income <= 3000) {
            return 1;
        }

        if (income <= 5000) {
            return 2;
        }

        if (income > 5000) {
            return 3;
        }
        return 0;
    }
}
